package com.hsgene.product.controller;

import com.google.common.collect.Lists;
import com.hsgene.common.ClientType;
import com.hsgene.common.DeleteFlagType;
import com.hsgene.common.exception.CommonErrorCode;
import com.hsgene.common.util.basic.SimpleStringUtils;
import com.hsgene.common.util.resolver.FromSession;
import com.hsgene.common.util.resolver.IgnoreUserToken;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.support.OrderHelper;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.order.domain.applets.AppletsOrderPackageInfoDto;
import com.hsgene.product.applets.dto.AppletsGoodsDetailsInfoDto;
import com.hsgene.product.applets.goods.AppletsErrorCode;
import com.hsgene.product.condition.CommodityCondition;
import com.hsgene.product.constants.CommodityShelfStatus;
import com.hsgene.product.dto.GeneticTestingCommodityDetailDto;
import com.hsgene.product.dto.wechat.SimpleCommodityDto;
import com.hsgene.product.exception.ProductErrorCode;
import com.hsgene.product.service.AppletsGoodsService;
import com.hsgene.product.service.CommodityService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 商品Controller
 *
 * @author wangbing
 * @version 1.0, 2018/10/11
 */
@RestController
@RequestMapping("/v1.0/genetic/testing/commodities")
public class CommodityController {

    private static Logger LOGGER = LogManager.getLogger(CommodityController.class);

    @Resource
    private CommodityService commodityService;

    @Resource
    private AppletsGoodsService appletsGoodsService;

    /**
     * 查询商品列表
     *
     * @param searchKey           搜索关键字（按名称模糊搜索）
     * @param commodityCategoryId 商品分类id
     * @param clientCommodityType 客户端（当前指小程序）商品分类：new-新品，hot-热卖，activity-活动，为空表示全部
     * @param shelfStatus         上架状态(0-下架  1-上架）
     * @param status              商品状态（0-待补充  1-未使用  2-已使用）
     * @param agencyId            检测机构id
     * @param orderBy             排序参数：composite（按综合排序：指最后修改时间），sales（按销量排序），prices(按价格排序）
     * @param isAsc               是否升序：true表示升序，false表示降序
     * @param pageNo              页号
     * @param pageSize            每页大小
     * @return 商品列表
     */
    @IgnoreUserToken(platform = 4)
    @GetMapping("")
    public ApiResult querySimpleCommodity(
            @RequestParam(name = "searchKey", required = false) String searchKey,
            @RequestParam(name = "commodityCategoryId", required = false) String commodityCategoryId,
            @RequestParam(name = "clientCommodityType", required = false) String clientCommodityType,
            @RequestParam(name = "shelfStatus", required = false) Integer shelfStatus,
            @RequestParam(name = "status", required = false) Integer status,
            @RequestParam(name = "agencyId", required = false) String agencyId,
            @RequestParam(name = "orderBy", defaultValue = "updateDateTime") String orderBy,
            @RequestParam(name = "isAsc", defaultValue = "false") Boolean isAsc,
            @RequestParam("page") int pageNo,
            @RequestParam("size") int pageSize,
            @RequestParam(name = "platform", defaultValue = "4") Integer platform) {
        CommodityCondition condition = new CommodityCondition();
        if (StringUtils.isNotBlank(searchKey)) {
            condition.setSearchKey(searchKey.trim());
        }
        condition.setCommodityCategoryId(commodityCategoryId);
        condition.setClientCommodityType(clientCommodityType);
        condition.setAgencyId(agencyId);
        condition.setDeleteFlag(DeleteFlagType.NOT_DELETED.getCode());
        OrderHelper orderHelper = OrderHelper.create(orderBy, isAsc);
        LimitHelper limitHelper = LimitHelper.create(pageNo, pageSize);
        ClientType clientType = ClientType.getEnum(platform);
        // CustomerSourceType requestSourceType = CustomerSourceType.getEnum(sourceType);
        if (ClientType.CONSOLE.equals(clientType)) {
            condition.setShelfStatus(shelfStatus);
            condition.setStatus(status);
            if (!"sales".equals(orderBy) && !"prices".equals(orderBy) && !"realPurchaseAmount".equals(orderBy) &&
                    !"originPrice".equals(orderBy) && !"updateDateTime".equals(orderBy)) {
                return ApiResult.fail(ProductErrorCode.SORT_COLUMN_IS_ERROR);
            }
            return commodityService.queryCommodityItems(condition, orderHelper, limitHelper);
        } else {
            condition.setShelfStatus(CommodityShelfStatus.ONLINE.getCode());
            return commodityService.querySimpleCommodity(condition, orderHelper, limitHelper);
        }
    }

    /**
     * @param userId 用户id
     * @return
     * @description 获取购物车商品数量
     * @author maodi
     * @createDate 2018/10/17 13:46
     */
    @GetMapping("getShoppingCarCommodityCount")
    public ApiResult<Integer> getShoppingCarCommodityList(@RequestParam("userId") String userId) {
        try {
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            return ApiResult.succ(commodityService.getShoppingCarCommodityCount(userId));
        } catch (NumberFormatException e) {
            LOGGER.error(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_COUNT_BY_USER_ID_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_COUNT_BY_USER_ID_IS_ERROR);
        }
    }

    /**
     * @param userId 用户id
     * @param page   页数
     * @param size   每页数量
     * @return
     * @description 获取购物车商品列表
     * @author maodi
     * @createDate 2018/10/17 13:46
     */
    @GetMapping("shopping_car")
    public ApiResult<Pagination<SimpleCommodityDto>> getShoppingCarCommodityList(@RequestParam("userId") String userId,
                                                                                 @RequestParam("page") String page,
                                                                                 @RequestParam("size") String size) {
        try {
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            if (StringUtils.isBlank(page)) {
                return ApiResult.fail(CommonErrorCode.PAGE_IS_NULL);
            }
            if (!SimpleStringUtils.isPositiveInteger(page)) {
                return ApiResult.fail(CommonErrorCode.PAGE_IS_NOT_POSITIVE_INTEGER);
            }
            if (StringUtils.isBlank(size)) {
                return ApiResult.fail(CommonErrorCode.SIZE_IS_NULL);
            }
            if (!SimpleStringUtils.isPositiveInteger(page)) {
                return ApiResult.fail(CommonErrorCode.SIZE_IS_NOT_POSITIVE_INTEGER);
            }
            LimitHelper limitHelper = LimitHelper.create(Integer.valueOf(page), Integer.valueOf(size));
            return ApiResult.succ(commodityService.getShoppingCarCommodityList(userId, limitHelper));
        } catch (NumberFormatException e) {
            LOGGER.error(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_LIST_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_LIST_IS_ERROR);
        }
    }

    /**
     * @param ids    id数组
     * @param userId 用户id
     * @return
     * @description 根据id数组获取购物车商品信息列表
     * @author maodi
     * @createDate 2018/10/17 15:08
     */
    @GetMapping("getShoppingCarCommodityListByIds")
    public ApiResult<List<SimpleCommodityDto>> getShoppingCarCommodityListByIds(@RequestParam("ids") String[] ids,
                                                                                @RequestParam("userId") String userId) {
        try {
            if (ids == null || ids.length < 1) {
                return ApiResult.fail(ProductErrorCode.COMMODITY_IDS_IS_NULL);
            }
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            return ApiResult.succ(commodityService.getShoppingCarCommodityListByIds(userId, ids));
        } catch (Exception e) {
            LOGGER.error(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_LIST_BY_IDS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_LIST_BY_IDS_IS_ERROR);
        }
    }

    /**
     * @param ids    id数组
     * @param userId 用户id
     * @return
     * @description 根据id数组获取购物车商品结算信息
     * @author maodi
     * @createDate 2018/10/17 15:09
     */
    @GetMapping("getShoppingCarCommodityBalanceByIds")
    public ApiResult<Map<String, Object>> getShoppingCarCommodityBalanceByIds(@RequestParam("ids") String[] ids,
                                                                              @RequestParam("userId") String userId) {
        try {
            if (ids == null || ids.length < 1) {
                return ApiResult.fail(ProductErrorCode.COMMODITY_IDS_IS_NULL);
            }
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            return ApiResult.succ(commodityService.getShoppingCarCommodityBalanceByIds(userId, ids));
        } catch (Exception e) {
            LOGGER.error(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_BALANCE_BY_IDS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_BALANCE_BY_IDS_IS_ERROR);
        }
    }

    /**
     * 根据套餐id查询商品信息
     *
     * @param packageId 套餐id
     * @return 商品详情信息
     */
    @IgnoreUserToken(platform = 4)
    @GetMapping("{packageId}")
    public ApiResult<Object> findCommodityByPackId(
            @PathVariable("packageId") String packageId, Integer platform,
            @FromSession UserInfo userInfo) {
        if (platform != null && platform.equals(ClientType.APPLETS.getCode())) {
            AppletsGoodsDetailsInfoDto detailsInfoDto = appletsGoodsService.getGoodsDetails(
                    packageId, userInfo == null ? null : userInfo.getUserId());
            if (detailsInfoDto == null) {
                return ApiResult.fail(AppletsErrorCode.PRODUCTS_INFO_IS_NOT_EXISTS);
            }
            return ApiResult.succ(detailsInfoDto, "获取商品详情成功");
        }
        return commodityService.findCommodityByPackageId(packageId);
    }

    /**
     * 更新套餐商品信息
     *
     * @param commodityDto 商品信息
     * @return 更新结果
     */
    @PutMapping("")
    public ApiResult<NullObject> updateCommodity(
            @RequestBody GeneticTestingCommodityDetailDto commodityDto) {
        return commodityService.updateCommodity(commodityDto);
    }

    /**
     * 新增套餐商品信息
     *
     * @param commodityDto 商品信息
     * @return 更新结果
     */
    @PostMapping("")
    public ApiResult<NullObject> addCommodity(
            @RequestBody GeneticTestingCommodityDetailDto commodityDto) {
        return commodityService.addCommodity(commodityDto);
    }

    /**
     * 根据套餐id删除商品信息
     *
     * @param packageIds 套餐id列表，多个id之间英文逗号分隔
     * @return 操作结果
     */
    @DeleteMapping("")
    public ApiResult<NullObject> deleteCommodity(
            @RequestParam("packageIds") String packageIds) {
        String[] packageIdArray = packageIds.split(",");
        if (packageIdArray.length > 1) {
            return commodityService.deleteCommodities(Lists.newArrayList(packageIdArray));
        }
        return commodityService.deleteCommodity(packageIds);
    }

    /**
     * 商品上下架管理
     *
     * @param packageId 商品套餐id
     * @param isShelf   true：上架；false：下架
     * @return 操作结果
     */
    @PutMapping("{packageId}/shelf")
    public ApiResult<NullObject> shelfCommodity(
            @PathVariable("packageId") String packageId,
            @RequestParam(name = "isShelf", defaultValue = "true") boolean isShelf) {
        return commodityService.shelfCommodity(packageId, isShelf);
    }

    /**
     * @param userId 用户id
     * @param ids    商品id数组
     * @return com.hsgene.order.domain.applets.AppletsOrderPackageInfoDto
     * @description 根据商品id获取小程序订单商品信息
     * @author maodi
     * @createDate 2018/10/18 11:30
     */
    @GetMapping("order/packages/infos")
    public ApiResult<List<AppletsOrderPackageInfoDto>> getAppletsOrderPackageInfoDtosByIds(
            @RequestParam(value = "userId", required = false) String userId, @RequestParam("ids") String[] ids) {
        try {
            if (ids.length < 1) {
                return ApiResult.fail(ProductErrorCode.GET_APPLETS_ORDER_PACKAGE_INFO_DTO_BY_IDS_IDS_IS_NULL);
            }
            List<AppletsOrderPackageInfoDto> list = commodityService.getAppletsOrderPackageInfoDtosByIds(userId, ids);
            if (CollectionUtils.isEmpty(list) || list.size() != ids.length) {
                return ApiResult.succ(new ArrayList<>());
            }
            return ApiResult.succ(list);
        } catch (Exception e) {
            LOGGER.error(ProductErrorCode.GET_APPLETS_ORDER_PACKAGE_INFO_DTO_BY_IDS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.GET_APPLETS_ORDER_PACKAGE_INFO_DTO_BY_IDS_IS_ERROR);
        }
    }

}
